package Client;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;


/**
 * ClientSender
 * 
 * Action listener for text field & key board
 * @author Yaxing Chen
 *
 */
public class ClientSender extends KeyAdapter implements ActionListener,FocusListener{
    private JTextField field;
    private JTextArea area;
    private DataOutputStream dos;
    private JButton button;
    private JButton clear;
    
    public ClientSender(DataOutputStream d,JTextField f,JButton b,JTextArea a,JButton c){
        field = f;
        dos = d;
        button = b;
        area = a;
        clear = c;
    }
    
    @Override
    public void keyTyped(KeyEvent e) {
          if(e.getKeyChar()==(char)KeyEvent.VK_ENTER){
            String s = field.getText();
            try{
                area.append("You said："+s+"\n");
                dos.writeUTF(s+"\n");
                if(s.equals("bye")){
                    dos.close();
                    area.setText("Exit！");
                    System.exit(-1);
                }
                field.setText("");
            }catch(IOException ee){
                ee.printStackTrace();
            }       
        }
    }
     public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("Send")){
            String s = field.getText();
            try{
                area.append("You said："+s+"\n");
                dos.writeUTF(s+"\n");
                if(s.equals("bye")){
                    dos.close();
                    area.setText("Exit！");
                    System.exit(-1);
                }
                field.setText("");
            }catch(IOException ee){
                ee.printStackTrace();
            }
        } 
        if(e.getActionCommand().equals("Clear")){
            area.setText("");
        }
    }

    public void focusGained(FocusEvent e) {
        Cursor cursor = new Cursor(Cursor.TEXT_CURSOR);
        field.requestFocusInWindow();
    }

    public void focusLost(FocusEvent e) {}
}